package cs575.common;

import java.nio.ByteBuffer;
import java.util.HashMap;

public class Player {
	public enum Position {
		QB(0), RB(1), WR(2), TE(3), K(4);

		private int value;

		private Position(int value) {
			this.value = value;
		}

		public static Position valueOf(int value) {
			for (Position p : Position.values()) {
				if (p.value == value) {
					return p;
				}
			}

			return null;
		}

	};

	private String name;
	private Position position;
	private HashMap<String, Integer> stats;

	public Player(String name, Position position) {
		this.name = name;
		this.position = position;
		stats = new HashMap<String, Integer>();
	}

	public Player(byte[] data) {
		fromBytes(data);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Position getPosition() {
		return position;
	}

	public void setPosition(Position position) {
		this.position = position;
	}

	public HashMap<String, Integer> getStats() {
		return stats;
	}

	public void setStats(HashMap<String, Integer> stats) {
		this.stats = stats;
	}

	public void updateStat(String statName, int statValue) {
		stats.put(statName, statValue);

	}

	/**
	 * Converts a Player object to a byte array for sending throughout the
	 * system.
	 * 
	 * @return Byte array containing Player data.
	 */
	public byte[] toBytes() {
		ByteBuffer bb = ByteBuffer.allocate(size());
		bb.putInt(position.value);
		bb.putInt(name.getBytes().length);
		bb.put(name.getBytes());
		bb.putInt(stats.size());

		for (String sName : stats.keySet()) {
			bb.putInt(sName.getBytes().length);
			bb.put(sName.getBytes());
			bb.putInt(stats.get(sName));
		}

		return bb.array();
	}

	private void fromBytes(byte[] array) {
		ByteBuffer bb = ByteBuffer.wrap(array);

		int positionInt = bb.getInt();
		position = Position.valueOf(positionInt);

		int nameSize = bb.getInt();
		byte[] nameBuffer = new byte[nameSize];
		bb.get(nameBuffer);

		this.name = new String(nameBuffer);

		int statsSize = bb.getInt();
		stats = new HashMap<String, Integer>(statsSize);

		for (int i = 0; i < statsSize; i++) {
			int stat;
			int sNameLength = bb.getInt();
			byte[] sName = new byte[sNameLength];
			bb.get(sName);
			stat = bb.getInt();
			stats.put(new String(sName), stat);
		}
		;
	}

	public int size() {
		// Position + Length of name, name, number of stats.
		int messageSize = 4 + 4 + name.getBytes().length + 4;
		for (String sName : stats.keySet()) {
			// Length of stat name, stat name, value
			messageSize += 4 + sName.getBytes().length + 4;
		}
		return messageSize;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();

		sb.append(name + " - " + position.toString());

		return sb.toString();
	}
}
